package org.zergle.utils;

import org.zergle.Filter;

/**
 * 文本操作实用类
 * 
 * @author Johnson.Lee
 */
public class Text {

	/**
	 * not visible
	 */
	private Text() {
	}

	/**
	 * 将字符串中单词首字母大写
	 * 
	 * @param str
	 *            字符串
	 * @return 返回单词首字母大写的字符串
	 */
	public static String cap(String str) {
		char[] literals = str.toCharArray();
		boolean beCap = true;
		for (int i = 0; i < literals.length; i++) {
			if (beCap) {
				if (Character.isLowerCase(literals[i])) {
					literals[i] -= 32;
				}
			} else if (Character.isUpperCase(literals[i])) {
				literals[i] += 32;
			}
			beCap = !Character.isLetter(literals[i]);
		}
		return new String(literals);
	}

	/**
	 * 转义字符串
	 * 
	 * @param str
	 *            字符串
	 * @return 转义后的字符序列
	 * @see Text#escape(char)
	 * @see Text#escape(CharSequence, Filter)
	 */
	public static CharSequence escape(CharSequence str) {
		StringBuffer buff = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			buff.append(escape(c));
		}
		return buff;
	}

	/**
	 * 转义字符串。当{@link Filter#accept(Object)}返回true时，则对字符进行转义，否则不转义。
	 * 
	 * @param str
	 *            字符串
	 * @param filter
	 *            字符过滤器
	 * @return 转义后的字符序列
	 * @see Text#escape(char)
	 * @see Text#escape(CharSequence)
	 */
	public static CharSequence escape(CharSequence str, Filter<Character> filter) {
		StringBuffer buff = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			buff.append(filter.accept(c) ? escape(c) : c);
		}
		return buff;
	}

	/**
	 * 转义字符
	 * 
	 * @param c
	 *            字符
	 * @return 返回转义后的字符串
	 * @see Text#escape(CharSequence)
	 * @see Text#escape(CharSequence, Filter)
	 */
	public static CharSequence escape(char c) {
		StringBuffer buff = new StringBuffer();
		switch (c) {
		case '/':
			buff.append("\\/");
			break;
		case '"':
			buff.append("\\\"");
			break;
		case '\\':
			buff.append("\\\\");
			break;
		case '\b':
			buff.append("\\b");
			break;
		case '\r':
			buff.append("\\r");
			break;
		case '\n':
			buff.append("\\n");
			break;
		case '\t':
			buff.append("\\t");
			break;
		case '\f':
			buff.append("\\f");
			break;
		default:
			buff.append(c);
			break;
		}
		return buff;
	}

	/**
	 * 将字符串转为unicode编码
	 * 
	 * @param str
	 *            字符串
	 * @return 返回字符串的unicode格式
	 */
	public static String unicode(CharSequence str) {
		StringBuffer buff = new StringBuffer();
		char[] unicode = new char[] { '\\', 'u', '0', '0', '0', '0' };
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			String hex = Integer.toHexString(c).toUpperCase();
			for (int j = 0; j < hex.length(); j++) {
				unicode[6 - hex.length() + j] = hex.charAt(j);
			}
			buff.append(unicode);
		}
		return buff.toString();
	}

}
